﻿using System;
using System.IO;
using NguyenHoa.Web.App_Code;
using NguyenHoa.Domains;
using NguyenHoa.Services;

namespace NguyenHoa.Web.Admin
{
  public partial class NewsList : AdminBasePage
  {
    #region Properties

    internal override int RequiredPermission
    {
      get
      {
        switch (NewsType)
        {
          case NewsCategoryType.Normal:
            return (int)FunctionList.AdNews;
          //case NewsCategoryType.Promotion:
          //  return (int)FunctionList.Promotion;
        }
        return (int)FunctionList.AdNews;
      }
    }

    private string NewsType
    {
      get
      {
        string newsType = string.Empty;
        if (!String.IsNullOrEmpty(Request.QueryString["t"]))
          newsType = Request.QueryString["t"].ToUpper();
        if (newsType != NewsCategoryType.Normal && newsType != NewsCategoryType.Promotion)
          return string.Empty;
        return newsType;
      }
    }

    private int? CategoryId
    {
      get
      {
        int categoryId = -1;
        if (!String.IsNullOrEmpty(Request.QueryString["tid"]))
          int.TryParse(Request.QueryString["tid"], out categoryId);
        return (categoryId != -1) ? categoryId : (int?)null;
      }
    }

    #endregion

    #region Methods
    protected string FormatDate(object value, string format)
    {
      DateTime dt = DateTime.MinValue;
      DateTime.TryParse(value.ToString(), out dt);
      return dt > DateTime.MinValue ? dt.ToString(format) : "";
    }

    private void LoadSearch()
    {
      xdsStatus.DataFile = XmlStatusFile;
      xdsLanguage.DataFile = XmlStatusFile;
      DateTime now = DateTime.Now;
      dexFromDate.Date = new DateTime(now.Year, now.Month, 1);
      dexToDate.Date = now;
      hfTypeId.Value = NewsType;
      cbxLanguage.Value = CurrentLanguage.Id;
      cbxCategory.DataSource = new NewsService().GetAllNewsCategory(NewsType, CurrentLanguage.Id, CurrentLanguage.Id);
      cbxCategory.DataBind();
    }

    private void LoadNews()
    {
      DateTime? fromDate = null, toDate = null;
      int? itemCount = 0, languageId = null;
      int itemPerPage = GlobalCache.Instance.ItemPerPage;
      if (cbxLanguage.Value != null) languageId = Convert.ToInt32(cbxLanguage.Value);
      string status = null;
      bool hotNews = false;
      if (ckbHotNews.Checked)
        hotNews = true;
      if (cbxStatus.Value != null)
        status = cbxStatus.Value.ToString();
      if (dexFromDate.Value != null)
        fromDate = dexFromDate.Date;
      if (dexToDate.Value != null)
        toDate = dexToDate.Date;
      int? categoryId = null;
      if (cbxCategory.Value != null)
        categoryId = Convert.ToInt32(cbxCategory.Value);
      TList<Domains.News> newsList = new NewsService().GetNewsBySearch(categoryId, languageId, null, fromDate, toDate,
        status, hotNews, null, itemPerPage, pager.PageIndex + 1, NewsType, ref itemCount);
      pager.ItemCount = (itemCount != null) ? itemCount.Value : 0;
      pager.ItemsPerPage = itemPerPage;
      foreach (Domains.News news in newsList)
      {
        if (news.ViewCount == null)
          news.ViewCount = 0;
        if (!string.IsNullOrEmpty(news.ImagePath))
        {
          if (File.Exists(MapPath("../" + news.ImagePath)))
          {
            news.ImagePath = "../" + news.ImagePath;
          }
        }
      }
      rptNews.DataSource = newsList;
      rptNews.DataBind();
    }

    private string DeleteNews(int newsId)
    {
      try
      {
        new NewsService().Delete(newsId);
      }
      catch (Exception ex)
      {
        WriteLog("NewsList.aspx::Delete News", ex);
        return Resources.Messages.ERR0004;
      }
      return string.Empty;
    }

    #endregion

    #region Events
    private void InitPage()
    {
      if (string.IsNullOrEmpty(NewsType))
        Response.Redirect("NewsList.aspx?t=" + NewsCategoryType.Normal);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsCallback && !IsPostBack)
      {
        InitPage();
        if (!CanModify) btnAdd.Visible = false;
        if (!IsCallback && !IsPostBack)
        {
          hfCategoryId.Value = CategoryId.ToString();
          LoadSearch();
          LoadNews();
        }
      }
    }

    protected void pager_PageIndexChanged(object sender, EventArgs e)
    {
      LoadNews();
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
      LoadNews();
    }

    protected void ctrlCallback_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
    {
      string[] para = e.Parameter.Split('|');
      if (para[0] == "Delete")
      {
        int newsId = 0;
        int.TryParse(para[1], out newsId);
        e.Result = DeleteNews(newsId);
      }
    }
    #endregion
  }
}
